#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char name[4];
    int age;
} student;

int main(int argc, char** argv) {
    int fd;
    student *p_map;

    // 打开文件并检查错误
    fd = open("stu.txt", O_RDWR, 0777);
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    // mmap 映射并检查错误
    p_map = (student*)mmap(NULL, sizeof(student) * 10, 
                          PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p_map == (void*)-1) {
        perror("mmap failed");
        close(fd);
        exit(1);
    }

    for (int i = 0; i < 10; i++) {
        printf("name: %s age: %d\n", (p_map + i)->name, (p_map + i)->age);
    }

    munmap(p_map, sizeof(student) * 10);
    close(fd);
    return 0;
}
